package com.itjin.health.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itjin.health.common.BaseResponse;
import com.itjin.health.common.ResultUtils;
import com.itjin.health.domain.dto.FeedbackAddRequest;
import com.itjin.health.domain.dto.FeedbackQueryRequest;
import com.itjin.health.domain.dto.FeedbackUpdateRequest;
import com.itjin.health.domain.entity.UserFeedback;
import com.itjin.health.domain.vo.FeedbackVO;
import com.itjin.health.exception.BusinessException;
import com.itjin.health.exception.ErrorCode;
import com.itjin.health.service.UserFeedbackService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 用户反馈接口
 */
@RestController
@RequestMapping("/feedback")
@Api(tags = "用户反馈接口")
@Slf4j
public class FeedBackController {

  @Resource
  private UserFeedbackService userFeedbackService;

  /**
   * 添加反馈
   *
   * @param addRequest 添加请求
   * @param request    HTTP请求
   * @return 反馈ID
   */
  @PostMapping("/add")
  @ApiOperation(value = "添加反馈")
  public BaseResponse<Integer> addFeedback(@RequestBody FeedbackAddRequest addRequest,
      HttpServletRequest request) {
    // 检查用户是否登录
    Object userIdObj = request.getSession().getAttribute("userId");
    if (userIdObj == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }
    Integer userId = (Integer) userIdObj;

    // 调用服务
    Integer feedbackId = userFeedbackService.addFeedback(addRequest, userId);
    return ResultUtils.success(feedbackId);
  }

  /**
   * 删除反馈
   *
   * @param id      反馈ID
   * @param request HTTP请求
   * @return 删除结果
   */
  @PostMapping("/delete")
  @ApiOperation(value = "删除反馈")
  public BaseResponse<Boolean> deleteFeedback(@ApiParam(value = "反馈ID", required = true) @RequestParam Integer id,
      HttpServletRequest request) {
    // 检查用户是否登录
    Object userIdObj = request.getSession().getAttribute("userId");
    if (userIdObj == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }
    Integer userId = (Integer) userIdObj;

    // 检查是否为管理员
    String userRole = (String) request.getSession().getAttribute("userRole");
    boolean isAdmin = "管理员".equals(userRole) || "超级管理员".equals(userRole);

    // 管理员可以删除任何反馈，普通用户只能删除自己的反馈
    boolean result;
    if (isAdmin) {
      // 直接删除
      result = userFeedbackService.removeById(id);
    } else {
      // 需要验证所有权
      result = userFeedbackService.deleteFeedback(id, userId);
    }

    return ResultUtils.success(result);
  }

  /**
   * 更新反馈
   *
   * @param updateRequest 更新请求
   * @param request       HTTP请求
   * @return 更新结果
   */
  @PostMapping("/update")
  @ApiOperation(value = "更新反馈")
  public BaseResponse<Boolean> updateFeedback(@RequestBody FeedbackUpdateRequest updateRequest,
      HttpServletRequest request) {
    // 检查用户是否登录
    Object userIdObj = request.getSession().getAttribute("userId");
    if (userIdObj == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }
    Integer userId = (Integer) userIdObj;

    // 检查是否为管理员
    String userRole = (String) request.getSession().getAttribute("userRole");
    boolean isAdmin = "管理员".equals(userRole) || "超级管理员".equals(userRole);

    boolean result;
    // 如果是管理员，可以更新任何反馈，普通用户只能更新自己的反馈
    if (isAdmin) {
      // 转换为实体对象
      UserFeedback feedback = new UserFeedback();
      BeanUtils.copyProperties(updateRequest, feedback);

      // 直接更新
      result = userFeedbackService.updateById(feedback);
    } else {
      // 需要验证所有权
      result = userFeedbackService.updateFeedback(updateRequest, userId);
    }

    return ResultUtils.success(result);
  }

  /**
   * 根据ID获取反馈详情
   *
   * @param id      反馈ID
   * @param request HTTP请求
   * @return 反馈详情
   */
  @GetMapping("/get")
  @ApiOperation(value = "获取反馈详情")
  public BaseResponse<FeedbackVO> getFeedbackById(
      @ApiParam(value = "反馈ID", required = true) @RequestParam Integer id,
      HttpServletRequest request) {
    // 检查用户是否登录
    Object userIdObj = request.getSession().getAttribute("userId");
    if (userIdObj == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }

    FeedbackVO feedbackVO = userFeedbackService.getFeedbackById(id);
    return ResultUtils.success(feedbackVO);
  }

  /**
   * 获取当前用户的反馈列表
   *
   * @param queryRequest 查询请求
   * @param request      HTTP请求
   * @return 当前用户反馈列表
   */
  @GetMapping("/list/my")
  @ApiOperation(value = "获取当前用户的反馈列表")
  public BaseResponse<Page<FeedbackVO>> listMyFeedbacks(FeedbackQueryRequest queryRequest,
      HttpServletRequest request) {
    // 检查用户是否登录
    Object userIdObj = request.getSession().getAttribute("userId");
    if (userIdObj == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }
    Integer userId = (Integer) userIdObj;

    // 设置默认参数
    if (queryRequest == null) {
      queryRequest = new FeedbackQueryRequest();
    }

    Page<FeedbackVO> feedbackVOPage = userFeedbackService.listUserFeedbacks(queryRequest, userId);
    return ResultUtils.success(feedbackVOPage);
  }

  /**
   * 获取所有反馈列表（管理员使用）
   *
   * @param queryRequest 查询请求
   * @param request      HTTP请求
   * @return 所有反馈列表
   */
  @GetMapping("/list/all")
  @ApiOperation(value = "获取所有反馈列表", notes = "仅管理员可用")
  public BaseResponse<Page<FeedbackVO>> listAllFeedbacks(FeedbackQueryRequest queryRequest,
      HttpServletRequest request) {
    // 检查用户是否登录
    Object userIdObj = request.getSession().getAttribute("userId");
    if (userIdObj == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }

    // 检查是否为管理员
    String userRole = (String) request.getSession().getAttribute("userRole");
    boolean isAdmin = "管理员".equals(userRole) || "超级管理员".equals(userRole);
    if (!isAdmin) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无管理员权限");
    }

    // 设置默认参数
    if (queryRequest == null) {
      queryRequest = new FeedbackQueryRequest();
    }

    Page<FeedbackVO> feedbackVOPage = userFeedbackService.listAllFeedbacks(queryRequest);
    return ResultUtils.success(feedbackVOPage);
  }
}
